<template>
    <div>
        <h1>任务编辑</h1>
        <div style="margin-bottom: 20px;">
            <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto">
                <el-form-item label="年级：" prop="level">
                    <el-select clearable v-model="ruleForm.level" placeholder="年级">
                        <el-option :label="item.name" :value="item.value" v-for="item in levelStore.list" :key="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="标题：" prop="title">
                    <el-input v-model="ruleForm.title" placeholder="请输入任务标题" />
                </el-form-item>
                <el-form-item label="试卷：" prop="paperItems">
                    <el-table :data="ruleForm.paperItems" border style="width: 100%">
                        <el-table-column prop="subjectId" label="学科" width="80">
                            <template #default="scope">
                                <span v-if="subjectMap[scope.row.subjectId]">{{ subjectMap[scope.row.subjectId] }}</span>
                                <span v-else>{{ scope.row.subjectId }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="name" label="名称" />
                        <el-table-column prop="createTime" label="创建时间" width="200" />
                        <el-table-column fixed="right" label="操作" width="180">
                            <template #default="scope">
                                <el-button @click="handleEditPaper(scope.row, scope.$index)">编辑</el-button>
                                <el-button type="danger" @click="handleDelete(scope.$index)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-form-item>
            </el-form>
        </div>
        <div style="margin-left: 30px;">
            <el-button type="primary" @click="handleSubmit">提交</el-button>
            <el-button @click="handleReset">重置</el-button>
            <el-button type="success" @click="handleAddPaper">添加试卷</el-button>
        </div>
        <!-- 试卷选择弹窗预留，可后续实现 -->
        <el-dialog v-model="showPaperDialog" title="选择试卷" width="60%">
            <div style="margin-bottom: 16px; display: flex; align-items: center;">
                <span style="margin-right: 8px;">学科：</span>
                <el-select v-model="selectSubjectId" placeholder="请选择学科" style="width: 200px;">
                    <el-option v-for="item in subjectOptions" :key="item.id" :label="item.name + (item.levelName ? '（' + item.levelName + '）' : '')" :value="item.id" />
                </el-select>
                <el-button type="primary" style="margin-left: 12px;" @click="fetchPaperList">查询</el-button>
            </div>
            <el-table :data="paperList" border style="width: 100%" @selection-change="handlePaperSelect" :row-key="(row: any) => row.id" ref="paperTableRef" :default-sort="{prop: 'createTime', order: 'descending'}" :height="300">
                <el-table-column type="selection" width="50" />
                <el-table-column prop="id" label="Id" width="80" />
                <el-table-column prop="subjectId" label="学科" width="120">
                    <template #default="scope">
                        <span v-if="subjectMap[scope.row.subjectId]">{{ subjectMap[scope.row.subjectId] }}</span>
                        <span v-else>{{ scope.row.subjectId }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="name" label="名称" />
                <el-table-column prop="createTime" label="创建时间" width="180" />
            </el-table>
            <div v-if="paperList.length === 0" style="text-align:center; color:#888; padding: 16px;">暂无数据</div>
            <div style="margin-top: 16px; text-align: right;">
                <el-button @click="showPaperDialog = false">取消</el-button>
                <el-button type="primary" @click="addSelectedPapers">确定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import axios from 'axios'
import { useRoute, useRouter } from 'vue-router'
import { useLevelStore } from '@/stores/level'

const ruleFormRef = ref<FormInstance>()
const ruleForm = ref<{ level: string; title: string; paperItems: any[]; id: number | null }>(
  {
    level: '',
    title: '',
    paperItems: [],
    id: null
  }
)
const rules = ref<FormRules>({
    level: [
        { required: true, message: '请选择年级', trigger: 'change' }
    ],
    title: [
        { required: true, message: '请输入任务标题', trigger: 'blur' }
    ],
    paperItems: [
        { required: true, type: 'array', min: 1, message: '请添加至少一份试卷', trigger: 'change' }
    ]
})
const route = useRoute()
const router = useRouter()
const levelStore = useLevelStore()
const showPaperDialog = ref(false)
const subjectMap = ref<Record<string, string>>({})
const taskId = ref<number | null>(null)
const subjectOptions = ref<any[]>([])
const selectSubjectId = ref('')
const paperList = ref<any[]>([])
const selectedPapers = ref<any[]>([])
const paperTableRef = ref()

// 获取学科列表（用于显示学科名）
const getSubjectList = async () => {
    const res = await axios.post('/api/admin/education/subject/list')
    if (res.data && res.data.code === 1) {
        const arr = res.data.response || []
        const map: Record<string, string> = {}
        arr.forEach((item: any) => {
            map[item.id] = item.name + (item.levelName ? `(${item.levelName})` : '')
        })
        subjectMap.value = map
    }
}

// 获取所有学科选项
const getSubjectOptions = async () => {
    const res = await axios.post('/api/admin/education/subject/list')
    if (res.data && res.data.code === 1) {
        subjectOptions.value = res.data.response || []
    }
}

// 查询试卷列表
const fetchPaperList = async () => {
    if (!selectSubjectId.value) {
        ElMessage.warning('请先选择学科')
        return
    }
    const params = {
        subjectId: selectSubjectId.value,
        pageIndex: 1,
        pageSize: 20
    }
    const res = await axios.post('/api/admin/exam/paper/page', params)
    if (res.data && res.data.code === 1 && res.data.response) {
        paperList.value = res.data.response.list || []
    } else {
        paperList.value = []
    }
}

// 编辑模式回显
onMounted(async () => {
    if ((window as any).__subjectArr) {
        subjectOptions.value = (window as any).__subjectArr
        const map: Record<string, string> = {}
        subjectOptions.value.forEach((item: any) => {
            map[item.id] = item.name + (item.levelName ? `(${item.levelName})` : '')
        })
        subjectMap.value = map
    } else {
        await getSubjectList()
        subjectOptions.value = Object.values(subjectMap.value).map((name, idx) => ({
            id: Object.keys(subjectMap.value)[idx],
            name: name,
            levelName: ''
        }))
    }
    if (route.query.id) {
        taskId.value = Number(route.query.id)
        const res = await axios.get(`/api/admin/task/select/${taskId.value}`)
        if (res.data && res.data.code === 1) {
            const detail = res.data.response
            ruleForm.value.level = String(detail.gradeLevel)
            ruleForm.value.title = detail.title
            ruleForm.value.paperItems = detail.paperItems || []
            ruleForm.value.id = detail.id
        }
    }
})

// 提交任务（新增/编辑）
const handleSubmit = async () => {
    if (!ruleFormRef.value) return
    await ruleFormRef.value.validate(async (valid: boolean) => {
        if (!valid) return
        const params = {
            id: ruleForm.value.id,
            gradeLevel: Number(ruleForm.value.level),
            title: ruleForm.value.title,
            paperItems: ruleForm.value.paperItems
        }
        try {
            const res = await axios.post('/api/admin/task/edit', params)
            if (res.data && res.data.code === 1) {
                ElMessage.success('保存成功')
                router.push('/task/listView')
            } else {
                ElMessage.error(res.data?.message || '保存失败')
            }
        } catch (e: any) {
            ElMessage.error(e.message || '请求失败')
        }
    })
}

// 重置
const handleReset = () => {
    ruleForm.value.level = ''
    ruleForm.value.title = ''
    ruleForm.value.paperItems = []
    ruleForm.value.id = null
}

// 编辑试卷（可扩展弹窗编辑）
const handleEditPaper = (row: any, idx: number) => {
    ElMessage.info('可实现试卷编辑弹窗')
}

// 删除试卷
const handleDelete = (index: number) => {
    ruleForm.value.paperItems.splice(index, 1)
}

// 添加试卷（弹窗选择，后续可补充弹窗逻辑）
const handleAddPaper = () => {
    showPaperDialog.value = true
    paperList.value = []
    selectSubjectId.value = ''
    selectedPapers.value = []
}

// 选择试卷
const handlePaperSelect = (rows: any[]) => {
    selectedPapers.value = rows
}

// 添加选中的试卷到任务
const addSelectedPapers = () => {
    if (!selectedPapers.value.length) {
        ElMessage.warning('请至少选择一份试卷')
        return
    }
    // 去重：只添加未存在的试卷
    const existIds = ruleForm.value.paperItems.map((p: any) => p.id)
    const toAdd = selectedPapers.value.filter((p: any) => !existIds.includes(p.id))
    if (toAdd.length === 0) {
        ElMessage.info('所选试卷已全部存在')
        return
    }
    ruleForm.value.paperItems.push(...toAdd)
    showPaperDialog.value = false
    // 清空选择
    selectedPapers.value = []
    if (paperTableRef.value) paperTableRef.value.clearSelection()
}
</script>

<style>
.required-asterisk {
    color: #f56c6c;
    margin-right: 4px;
}
</style>
